package tinglema.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.DigestUtils;
import tinglema.server.common.AuthR;
import tinglema.server.common.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import tinglema.server.constants.Constants;
import tinglema.server.entity.domain.Consumer;
import tinglema.server.entity.request.UserRequest;
import tinglema.server.entity.view.UserView;
import tinglema.server.service.ConsumerService;
import org.springframework.web.bind.annotation.*;
import tinglema.server.utils.JwtUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Date;
import java.util.List;

/**
 * 用户表(Consumer)表控制层
 *
 * @author delucia
 * @since 2025-03-20 20:44:05
 */
@RestController
@RequestMapping("user")
public class ConsumerController {
    /**
     * 服务对象
     */
    @Resource
    private ConsumerService consumerService;

    /**
     * 分页查询所有数据
     *
     * @param page     分页对象
     * @param consumer 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<Consumer> page, Consumer consumer) {
        return R.success(this.consumerService.page(page, new QueryWrapper<>(consumer)));
    }

    /**
     * 分页查询所有数据
     *
     * @param current
     * @param size
     * @return 所有数据
     */
    @GetMapping("/page")
    public R selectByPage(@RequestParam int current, @RequestParam int size) {
        Page<Consumer> page = new Page<>(current, size);
        return R.success(this.consumerService.page(page));

    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return R.success(UserView.transter(this.consumerService.getById(id)));
    }

    /**
     * 新增数据
     *
     * @param consumer 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody Consumer consumer) {
        return R.success(this.consumerService.save(consumer));
    }

    /**
     * 修改数据
     *
     * @param consumer 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody Consumer consumer) {
        return R.success(this.consumerService.updateById(consumer));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public R deleteOne(@RequestParam("id") Long id) {
        return R.success(this.consumerService.removeById(id));
    }

    /**
     * @param idList 逗号分隔的id字符串 ?idList=2,3
     * @return
     */
    @DeleteMapping("/delete/batch")
    public R delete(@RequestParam("idList") List<Long> idList) {
        return R.success(this.consumerService.removeByIds(idList));
    }


    /******************** Client API *******************/

    /**
     * 用户登录状态验证
     *
     * @return 登录结果
     * @RequestBody ConsumerDTO 封装用户对象
     */
    @PostMapping("login/status")
    public R signIn(@RequestBody UserRequest user) {
        // TODO::前端加密还是后端加密
        // user.getPassword()
        LambdaQueryWrapper<Consumer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Consumer::getUsername, user.getUsername())
                .eq(Consumer::getPassword, user.getPassword());
        Consumer consumer = consumerService.getOne(queryWrapper);
        if (consumer != null) {
            // 适合单体架构(前后端不分离的) COOKIE/SESSION_ID
            // 微服务项目: TOKEN/分布式SESSION 默认保留30分钟
            // JWT = JSON WEB TOKEN 设置过期时间
            // SA-TOKEN
            String tokenStr = JwtUtils.generateToken(user.getUsername());
            AuthR token = new AuthR();
            token.setAuthorization(tokenStr);
            token.setObj(UserView.transter(consumer));
            return R.success("登录成功", token);
        } else {
            return R.error("用户名或密码错误");
        }
    }

    // 用户登录
    // post("user/add",{username,password,sex,phoneNum,email,birth,introduction,location})
    @PostMapping("add")
    public R add(@RequestBody UserRequest userRequest) {
        // 如果用户名已存在，则返回错误信息
        if (consumerService.getOne(new LambdaQueryWrapper<Consumer>().eq(Consumer::getUsername, userRequest.getUsername())) != null) {
            return R.error("用户名已存在");
        }
        // 用户名不存在, 则添加用户
        Consumer consumer = new Consumer();
        BeanUtils.copyProperties(userRequest, consumer);
        consumer.setAvator("/img/avatorImages/user.jpg");


        // 邮件地址判空处理
        if (StringUtils.isBlank(consumer.getEmail())) {
            consumer.setEmail(null);
        }

        if (consumer.getPhoneNum().trim().isEmpty()){
            consumer.setPhoneNum(null);
        }

        // 密码加密
        // String password = DigestUtils.md5DigestAsHex((Constants.SALT + userRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        // consumer.setPassword(password);


        try {
            if (consumerService.save(consumer)) {
                return R.success("注册成功");
            } else {
                return R.error("注册失败");
            }
        } catch ( DuplicateKeyException e) {
            return R.error(e.getMessage());
        }

    }
}
